<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.categoryId ? $t('crud.addTitle') : $t('groups.edit')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="auto"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        v-if="dataForm.type !== 2 && isSecondLevel === false"
        :label="$t('category.categoryPicture')"
        :required="isRequiredImg"
        prop="pic"
      >
        <div>
          <img-upload
            v-model:model-value="dataForm.pic"
            @update:model-value="imgChange(dataForm.pic, 'pic')"
          />
          <div>{{ $t('admin.recommImgSize') + '532*160' }}</div>
        </div>
      </el-form-item>

      <el-form-item
        v-if="dataForm.type !== 2"
        :label="$t('publics.categoryCn')"
        prop="categoryName"
      >
        <el-input
          v-model.trim="dataForm.categoryName"
          controls-position="right"
          :min="0"
          maxlength="50"
          show-word-limit
          :label="$t('publics.categoryCn')"
        />
      </el-form-item>

      <el-form-item
        v-if="dataForm.type !== 2"
        :label="$t('publics.categoryEn')"
        prop="categoryNameEn"
      >
        <el-input
          v-model="dataForm.categoryNameEn"
          controls-position="right"
          :min="0"
          maxlength="50"
          show-word-limit
          :label="$t('publics.categoryEn')"
        />
      </el-form-item>

      <el-form-item :label="$t('category.categoryParent')">
        <el-cascader
          :key="cascaderKey"
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :disabled="pickerDisabled || dataForm.categoryId"
          change-on-select
          :clearable="true"
          @change="onHandleChange"
        />
        <div
          class="category-parent-tip"
        >
          {{ $t('category.AfterCreatingDisabled') }}
        </div>
      </el-form-item>

      <el-form-item
        v-if="dataForm.type !== 2"
        :label="$t('hotSearch.seq')"
        prop="seq"
      >
        <el-input-number
          v-model="dataForm.seq"
          controls-position="right"
          :min="0"
          :label="$t('hotSearch.seq')"
        />
      </el-form-item>

      <el-form-item
        :label="$t('product.status')"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">
            {{ $t('publics.offline') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('publics.normal') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import ImgUpload from '@/components/img-upload/index.vue'
import { defineExpose } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const pickerDisabled = ref(false)
const isSecondLevel = ref(false)
const dataForm = reactive({
  categoryId: 0,
  grade: 0,
  categoryName: '',
  categoryNameEn: '',
  seq: 1,
  status: 1,
  parentId: 0,
  pic: ''
})
let isSubmit = false
const categoryList = ref([])
const selectedCategory = ref([])
const categoryTreeProps = {
  value: 'categoryId', // 指定选项的值为选项对象的某个属性值
  label: 'categoryName', // 指定选项标签为选项对象的某个属性值
  checkStrictly: true // 是否严格的遵守父子节点不互相关联
}

const isRequiredImg = ref(false) // 图片分类一级不必填
const cascaderKey = ref('cascaderKey')

// eslint-disable-next-line no-unused-vars
const validateCategoryName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('publics.categoryNoNull')))
  } else {
    callback()
  }
}
// 一级分类图片不必传
// eslint-disable-next-line no-unused-vars
const validNoEmptyImg = (rule, value, callback) => {
  if (selectedCategory.value.length > 0 && !value) {
    callback(new Error($t('publics.imageNoNull')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  categoryName: [
    { required: true, message: $t('publics.categoryNoNull'), trigger: 'blur' },
    { validator: validateCategoryName, trigger: 'blur' }
  ],
  pic: [
    { validator: validNoEmptyImg, trigger: 'blur' }
  ]
})

watch(
  dataForm,
  () => {
    if (dataForm.type !== 2 && isSecondLevel.value) {
      dataForm.pic = ''
    }
  },
  { deep: true }
)

watch(selectedCategory, val => {
  isRequiredImg.value = !!val?.length
})

const dataFormRef = ref(null)
const init = id => {
  if (!id) {
    // 用于判断分类图标是否显示
    dataForm.parentId = 0
  }
  dataForm.categoryId = id || 0
  isSecondLevel.value = false
  isSubmit = false
  pickerDisabled.value = false
  http({
    url: http.adornUrl('/prod/category/upAndCurrCategoryList/' + dataForm.categoryId),
    method: 'get',
    params: http.adornParams({
      maxGrade: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  }).then(() => {
    visible.value = true
    nextTick(() => {
      dataFormRef.value?.resetFields()
      selectedCategory.value = []
    })
  }).then(() => {
    if (dataForm.categoryId) {
      // 修改
      http({
        url: http.adornUrl(`/prod/category/info/${dataForm.categoryId}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        isSecondLevel.value = data.grade === 1
        dataForm.categoryId = data.categoryId
        dataForm.categoryName = data.categoryName
        dataForm.categoryNameEn = data.categoryNameEn
        dataForm.seq = data.seq
        dataForm.pic = data.pic
        dataForm.parentId = data.parentId
        dataForm.status = data.status
        selectedCategory.value = idList(
          categoryList.value,
          data.parentId,
          'categoryId',
          'children'
        ).reverse()
      })
    }
  })
}

const onHandleChange = val => {
  if (val) {
    isSecondLevel.value = val.length === 1
    dataForm.parentId = val[val.length - 1]
    if (!dataForm.parentId && dataForm.parentId !== 0) {
      dataForm.parentId = 0
    }
  } else {
    isSecondLevel.value = false
    dataForm.parentId = 0
  }
  cascaderKey.value = Math.random() * 10000000000000
}

/**
 * 图片的值发生改变，重新校验对应表单字段
 * @param {String} value 改变的值
 * @param {String} prop 校验字段
 */
const imgChange = (value, prop) => {
  if (value) {
    dataFormRef.value?.validateField(prop)
  }
}

// 表单提交
const onSubmit = () => {
  if (selectedCategory.value.length === 1) {
    dataForm.grade = 1
  } else if (selectedCategory.value.length === 2) {
    dataForm.grade = 2
  } else {
    dataForm.grade = 0
  }
  dataFormRef.value?.validate(valid => {
    if (valid) {
      if (isSubmit) {
        return false
      }
      isSubmit = true
      pickerDisabled.value = true
      http({
        url: http.adornUrl('/prod/category'),
        method: dataForm.categoryId ? 'put' : 'post',
        data: http.adornData({
          categoryId: dataForm.categoryId || undefined,
          categoryName: dataForm.categoryName,
          categoryNameEn: dataForm.categoryNameEn,
          status: dataForm.status,
          seq: dataForm.seq,
          grade: dataForm.grade,
          parentId: dataForm.parentId,
          pic: dataForm.pic
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit = false
        pickerDisabled.value = false
      })
    }
  })
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.category-parent-tip {
  display: inline-block;
  background: #fffcf2;
  border: 1px solid #f6c023;
  padding: 5px;
  font-size: 12px;
  color: #666;
  line-height: 1.5em;
  margin-left: 5px;
}
</style>
